package com.dianwoba.core.solr.where;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * 复杂WHERE
 * @author 堵成杰
 * @since 2.0
 */
public class SolrComplexWhere extends AbstractSolrWhere<SolrComplexWhere> {
	
	protected List<String> allCriteriaList = new LinkedList<String>();

	/**
	 * OR条件设定
	 * @return 
	 */
	public SolrComplexWhere or(){
		flushCriteria();
		return this;
	}

	private void flushCriteria() {
		allCriteriaList.add(" OR (" + getCriteriaCore() + ")");
		criteriaList = new ArrayList<String>();
		mergeCandidateConditions = new HashMap<String, Condition>();
	}

	/**
	 * OR条件设定
	 * @return 
	 */
	public SolrComplexWhere or(SolrWhere factor){
		if(StringUtils.isEmpty(factor.getCriteria())){
			return this;
		}
		if(hasCondition()){
			flushCriteria();
		}
		allCriteriaList.add(" OR (" + factor.getCriteria() + ")");

		if(!containsNot){
			containsNot = factor.containsNot();
		}
		return this;
	}


	/**
	 * 设定and条件
	 * @param factor 
	 * @return 
	 */
	public SolrComplexWhere and(SolrWhere factor){
		if(StringUtils.isEmpty(factor.getCriteria())){
			return this;
		}
		if(hasCondition()){
			flushCriteria();
		}
		//allCriteriaList.add(" AND (" + factor.getCriteria() + ")");
		//System.out.println("factor.getCriteria():"+factor.getCriteria().indexOf("region") );
		if(factor.getCriteria().indexOf("region")!=-1){//区块过滤特殊处理
			allCriteriaList.add(" AND " + factor.getCriteria() + "");
		}
		else{
			allCriteriaList.add(" AND (" + factor.getCriteria() + ")");
		}
		if(!containsNot){
			containsNot = factor.containsNot();
		}

		return this;
	}

	/**
	 * not and 条件设定
	 * @param factor 
	 * @return 
	 */
	public SolrComplexWhere not(SolrWhere factor){
		if(StringUtils.isEmpty(factor.getCriteria())){
			return this;
		}
		if(hasCondition()){
			flushCriteria();
		}
		allCriteriaList.add(" AND NOT (" + factor.getCriteria() + ")");
		containsNot = true;

		return this;
	}


	@Override
	public String getCriteria() {

		if(criteria != null){
			return criteria;
		}

		if(hasCondition()){
			allCriteriaList.add(" OR (" + getCriteriaCore() + ")");
		}

		StringBuilder builder = new StringBuilder();
		for (String tmpCriteria : allCriteriaList) {
			builder.append(tmpCriteria);
		}
		String result = builder.toString();

		if(result.startsWith(" OR ")){
			criteria = builder.toString().substring(4);
		}else if(result.startsWith(" AND ")){
			criteria = builder.toString().substring(5);
		}

		return criteria;

	}

	protected boolean hasCondition(){
		return criteriaList.size() > 0 || !mergeCandidateConditions.isEmpty();
	}

}
